// 发送api请求
import md5 from 'blueimp-md5'
import qs from 'qs'
import { isObjectLike, split, indexOf } from 'lodash'
import storeage from '@/tools/storage'
import { BASE_URL, INDEX_URL } from '@/config/const.js'
import axiosObj from '@/tools/axiosObj.js'
import store from '@/store'
// import notify from '@/tools/notify'
import {
  SUCCESS_STATUS_ARR,
  NEED_LOGIN_STATUS,
  TOKEN_FAILURE_STATUS,
  LIMIT_AUTH_STATUS,
  NULL_DATA_STATUS,
  VERIFY_ERR_STATUS,
  SUCCESS_STATUS,
  ERR_STATUS
} from '@/config/status'
import * as types from '@/store/mutation-types'
import { Loading } from 'element-ui'

// 处理数据 并返回
const _createData = (pathObj, data) => {
  let sendTime = (Date.parse(new Date()) + '').substring(0, 10)
  let keyA = sendTime.substring(0, 5)
  let keyB = sendTime.substring(5, 10)
  let encryption = 'off'
  // 在此获取token
  let token = store.state.auth.token
  return {
    appkey: md5(pathObj.ver + keyA + encryption + pathObj.module + keyB + pathObj.controller + pathObj.action + token),
    sendTime: sendTime,
    ver: pathObj.ver,
    module: pathObj.module,
    controller: pathObj.controller,
    action: pathObj.action,
    encryption: encryption,
    textData: JSON.stringify(data),
    token: token
  }
}

// 路径解析
const _pathResolver = (path) => {
  let arr = split(path, '/', 4)
  return {
    ver: arr[0],
    module: arr[1],
    controller: arr[2],
    action: arr[3]
  }
}
// 暂时先没有用到
let configDefault = {
  loading: false,
  loadingText: '数据载入中...',
  successStatusArr: SUCCESS_STATUS_ARR
}
// 载入动画的次数
let loadingTime = 0
let loadingObj = {close () {}}
// post发送数据
const api = async (path, data = {}, config = {}) => {
  // notify.success(path)
  // 合并配置
  config = {...configDefault, ...config}
  // 先判断path是否是对象类型,如果是
  if (isObjectLike(path)) {
    data = path
    path = data.path
  }
  // 解析path 为 ver,module,controller,action
  let pathObj = _pathResolver(path)
  // 创建发送对象
  let sendData = _createData(pathObj, data)
  if (!sendData.token || sendData.token.length !== 32) {
    store.dispatch('layout/set', {msg: 'token无效,未发送请求sendData', status: VERIFY_ERR_STATUS})
    console.log('token无效,未发送请求sendData:', sendData)
    return {}
  }
  if (config.loading) {
    loadingTime += 1
    loadingObj = Loading.service({text: config.loadingText})
    store.dispatch('layout/set', {msg: config.loadingText, status: SUCCESS_STATUS})
  }
  // 返回Promise对象
  let res = await axiosObj.post(BASE_URL + INDEX_URL, qs.stringify(sendData))
  if (config.loading) {
    loadingTime -= 1
    store.dispatch('layout/set', {msg: '已完成' + config.loadingText, status: SUCCESS_STATUS})
    if (loadingTime === 0) {
      loadingObj.close()
      store.dispatch('layout/set', {msg: '已完成所有api请求...', status: SUCCESS_STATUS})
    }
  }
  if (res.status !== 200) {
    let msg = '请求接口' + path + '网络异常:' + res.statusText
    // notify.warning(msg)
    store.dispatch('layout/set', {msg: msg, status: ERR_STATUS})
    return {}
  }
  let msg = res.data.msg
  // 如果token失效
  if (TOKEN_FAILURE_STATUS === res.data.status) {
    storeage.clearAll()
    store.state.auth.token = ''
    msg = '已清除token,' + msg
  } else if (NEED_LOGIN_STATUS === res.data.status) {
    console.log('需要登录:', res.data)
    storeage.remove(types.USER_INFO)
    store.dispatch('layout/set', {msg: '需要登录', status: res.data.status})
    store.dispatch('user/clearUserInfo')
    return res.data
  } else if (LIMIT_AUTH_STATUS === res.data.status) {
    console.log('权限不足:', res.data)
    msg = '权限不足,' + msg
    res.data.res = {}
    return res.data
  } else if (res.data.status === NULL_DATA_STATUS) {
    console.log('没有数据:', res.data, 1)
    // res.data.res = {}
    msg = '没有数据' + msg
  } else if (indexOf(config.successStatusArr, res.data.status) === -1) {
    // 如果请求的接口返回的状态码属于失败状态码数组之内,则弹出提示
    msg = '请求接口' + path + ':' + res.data.msg
    // notify.warning(msg)
  }
  store.dispatch('layout/set', {msg: msg, status: res.data.status})
  return res.data
}

export default api
